//
//  NetWorkEngine.m
//  TriumphInTheSkiesAPP
//
//  Created by iMacOne on 15/11/3.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "NetWorkEngine.h"
#import "AFNetworking.h"
#import "ToolUtil.h"
@implementation NetWorkEngine

//get请求
- (void)get:(NSString *)urlString
{
    NSString * urlStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] init];
    NSDictionary * dict = @{@"format":@"json"};
    AFHTTPRequestOperation * operation = [manager GET:urlString parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (self.delegate) {
            NSDictionary * resultDic = responseObject;
            [_delegate NetWorkDidSuccessful:resultDic];
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_delegate NetWorkDidFail:error];
    }];
    
    
    
}
//post请求
- (void)post:(NSString *)urlString paramsString:(NSString *)paramsString
{
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/css", @"text/plain", nil]];
    AFHTTPRequestOperation * operation = [manager POST:urlString parameters:paramsString success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError * error = nil;
        NSDictionary * resultDic = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];
        if (error == nil) {
            [_delegate NetWorkDidSuccessful:resultDic];
        }else{
            NSLog(@"POST方式解析出错");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_delegate NetWorkDidFail:error];
        
    }];
    
}
//传入一个post的参数字符串得到一个字典
- (NSDictionary *)getParamsFromParamString:(NSString *)paramsString
{
    paramsString = [paramsString stringByReplacingOccurrencesOfString:@"" withString:@""];
    NSMutableDictionary * paraDic = [NSMutableDictionary dictionary];
    NSArray * array = [paramsString componentsSeparatedByString:@"&"];
    for (NSString * str in array) {
        NSArray * smallArray = [str componentsSeparatedByString:@"="];
        [paraDic setObject:[smallArray lastObject] forKey:[smallArray firstObject]];
    }
    return [NSDictionary dictionaryWithDictionary:paraDic];
}
//停止加载
- (void)stopLoading
{
    [_manager.operationQueue cancelAllOperations];
}

//+ (void)jump:(NSString *)fromText to:(UIViewController *)toVC
//{
//    if (toVC == nil) {
//        NSLog(@"hlj");
//    }
//}

@end
